package com.neutech.dao.impl;

import com.neutech.constant.Constant;
import com.neutech.dao.AdminDAO;
import com.neutech.entity.Admin;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;


public class AdminDAOImpl implements AdminDAO {

    private QueryRunner queryRunner =new QueryRunner(Constant.dateSource);

    @Override
    public Admin selectByAdminName(String adminName) {
        final Admin admin = new Admin();

        try {
            queryRunner.execute("select * from admin where admin_name = ?",
                    new ResultSetHandler<Object>() {
                        @Override
                        public Object handle(ResultSet resultSet) throws SQLException {
                            if (resultSet.next()){

                                admin.setAdminId(resultSet.getInt("admin_id"));
                                admin.setAdminName(resultSet.getString("admin_name"));
                                admin.setPassword(resultSet.getString("password"));

                            }
                            return admin;
                        }
                    },adminName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return admin;
    }

    @Override
    public int insert(Admin admin) {
        int row =0;
        try {
            row = queryRunner.execute("insert into admin(admin_name,password) values(?,?)",
                    admin.getAdminName(),admin.getPassword());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return row;
    }
}
